<script setup lang="ts">
import {reactive, ref, onMounted, computed} from 'vue'
import {type CascaderProps, message} from 'ant-design-vue'
import {getTeachAndLearn, listUserByRecommend, listUserVoByPage} from '@/api/userController.ts'
import {useRouter} from 'vue-router'
import UserListCard from "@/components/UserListCard.vue";
import {ReloadOutlined} from '@ant-design/icons-vue';

// 路由实例
const router = useRouter()
const options: CascaderProps['options'] = ref()


// 搜索参数
const searchParams = reactive<API.UserQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'create_time',
  sortOrder: 'ascend',
  searchText: '',
  teach: [],
  learn: [],
})

// 匹配模式
const matchMode = ref('recommend')


// 用户列表数据
const userList = ref<API.UserVO[]>([])

// 总用户数
const total = ref(0)

// 加载状态
const loading = ref(false);


// 获取匹配用户数据
const fetchMatchUsers = async (isRefresh: boolean = false) => {
  loading.value = true;
  try {
    //实际得到的是二维数组，需处理
    const queryParams = {
      ...searchParams,
      isRefresh: isRefresh,
      // 假设只想提交最后一级（子节点）的值
      teach: searchParams.teach ? searchParams.teach.map((item: string[]) => item[item.length - 1]) : [],
      learn: searchParams.learn ? searchParams.learn.map((item: string[]) => item[item.length - 1]) : []
    };


    const res = await listUserByRecommend(queryParams)

    if (res.data.code === 0 && res.data.data) {
      total.value = res.data.data.total || 0
      userList.value = res.data.data.records
      console.log('获取匹配用户成功：', res.data.data)
    } else {
      message.error('获取匹配用户失败：' + res.data.message)
    }
  } catch (error) {
    console.error('获取匹配用户异常：', error)
    message.error('获取匹配用户异常，请稍后重试')
  } finally {
    loading.value = false;
  }
}

// 搜索用户
const doSearch = () => {
  searchParams.current = 1
  fetchMatchUsers()
}

// 重置筛选条件
const resetFilters = () => {
  searchParams.searchText = ''
  searchParams.teach = []
  searchParams.learn = []
  matchMode.value = 'recommend'
  searchParams.current = 1
  fetchMatchUsers()
}

// 处理匹配模式变更
const handleMatchModeChange = () => {
  searchParams.current = 1
  fetchMatchUsers()
}


// 处理分页变化
const handlePaginationChange = (page: number) => {
  searchParams.current = page
  fetchMatchUsers()
}

// 处理每页显示数量变化
const handlePageSizeChange = (current: number, pageSize: number) => {
  searchParams.current = current
  searchParams.pageSize = pageSize
  fetchMatchUsers()
}
const getTeachAndLearnOptions = async () => {
  const res = await getTeachAndLearn()
  if (res.data.code === 0 && res.data.data) {
    // 使用 Object.entries 将对象转换为可遍历的键值对数组
    options.value = Object.entries(res.data.data).map(([parentKey, childrenValues]) => {
      return {
        value: parentKey, // 使用父级的键作为 value，如 "计算机"
        label: parentKey, // 使用父级的键作为显示标签，如 "计算机"
        children: childrenValues.map(childValue => {
          return {
            value: childValue, // 使用子项的值作为 value，如 "java"
            label: childValue  // 使用子项的值作为显示标签，如 "java"
          }
        })
      }
    })
    console.log('转换后的 options:', options.value) // 添加日志，调试时非常有用
  } else {
    message.error('获取选项失败' + res.data.message)
  }
}
onMounted(() => {
  getTeachAndLearnOptions()
  fetchMatchUsers()
})
</script>
<template>
  <div id="MatchPage">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="title">厚米匹配</h2>
      <p class="subtitle">寻找志同道合的学习伙伴</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-container">
      <a-form layout="inline" :model="searchParams" @submit="doSearch">
        <a-form-item label="搜索">
          <a-input
              v-model:value="searchParams.searchText"
              placeholder="搜索用户"
              allow-clear
          />
        </a-form-item>
        <a-form-item
            label="他能教"
            name="teach">
          <a-cascader
              v-model:value="searchParams.teach"
              style="width: 200px"
              multiple
              max-tag-count="responsive"
              :options="options"
              placeholder="他能教的技能"
          />
        </a-form-item>
        <a-form-item
            label="他想学"
            name="learn">
          <a-cascader
              v-model:value="searchParams.learn"
              style="width: 200px"
              multiple
              max-tag-count="responsive"
              :options="options"
              placeholder="他想学习的技能"
          />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit">搜索</a-button>
        </a-form-item>

        <a-form-item>
          <a-button @click="resetFilters">重置</a-button>
        </a-form-item>
      </a-form>

      <!--      &lt;!&ndash; 匹配设置 &ndash;&gt;-->
      <!--      <div class="match-settings">-->
      <!--        <div class="setting-item">-->
      <!--          <span>匹配模式:</span>-->
      <!--          <a-radio-group v-model:value="matchMode" @change="handleMatchModeChange">-->
      <!--            <a-radio value="recommend">智能推荐</a-radio>-->
      <!--            <a-radio value="nearby">附近用户</a-radio>-->
      <!--            <a-radio value="latest">最新注册</a-radio>-->
      <!--          </a-radio-group>-->
      <!--        </div>-->
      <!--      </div>-->
    </div>

    <!-- 用户匹配列表 -->
    <div class="match-results">
      <div class="results-header">
        <h3>匹配结果</h3>
        <div style="display: flex; align-items: center; gap: 15px;">
          <span class="results-count">{{ total }} 位匹配用户</span>
          <a-button @click="fetchMatchUsers(true)" :loading="loading" size="small">
            <template #icon>
              <ReloadOutlined/>
            </template>
            刷新
          </a-button>
        </div>
      </div>

      <!-- 匹配列表为空时显示 -->
      <div v-if="!userList.length" class="empty-state">
        <a-empty description="暂无匹配的用户"/>
        <p class="empty-tips">尝试调整搜索条件或匹配模式</p>
      </div>

      <!-- 用户卡片列表 -->
      <UserListCard v-else :userList="userList"/>

      <!-- 分页控件 -->
      <!--      <div v-if="userList.length" class="pagination-container">-->
      <!--        <a-pagination-->
      <!--            v-model:current="searchParams.current"-->
      <!--            v-model:pageSize="searchParams.pageSize"-->
      <!--            :pageSize-options="['10', '20', '50']"-->
      <!--            :total="total"-->
      <!--            showSizeChanger-->
      <!--            showQuickJumper-->
      <!--            showTotal="(total) => `共 ${total} 条数据`"-->
      <!--            @change="handlePaginationChange"-->
      <!--            @showSizeChange="handlePageSizeChange"-->
      <!--        />-->
      <!--      </div>-->
      <a-pagination
          style="text-align: right"
          v-model:current="searchParams.current"
          v-model:pageSize="searchParams.pageSize"
          :total="total"
          @change="handlePageSizeChange"
      />
    </div>
  </div>
</template>


<style scoped>
#MatchPage {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.title {
  font-size: 28px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 16px;
  color: #666;
}

.search-filter-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.match-settings {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.setting-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.setting-item span {
  margin-right: 15px;
  min-width: 80px;
}


.match-results {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.results-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.results-count {
  color: #666;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.empty-tips {
  margin-top: 10px;
  color: #999;
}


.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-cards-grid {
    grid-template-columns: 1fr;
  }

  .search-filter-container .a-form-inline {
    flex-direction: column;
  }

  .search-filter-container .a-form-item {
    margin-bottom: 15px;
    width: 100%;
  }
}
</style>
